/*
 * Author: Michael Lewis <mikelikespie@gmail.com>
 * License: GPL v2 <http://www.opensource.org/licenses/gpl-license.php>
 */
#import "MessageView.h"
#import <CoreFoundation/CoreFoundation.h>
#import <UIKit/UITableColumn.h>
#import <UIKit/UIImageAndTextTableCell.h>
#import <GraphicsServices/GraphicsServices.h>
#import <pthread.h>
#import "sqlite3.h"
#import "Message.h"
#import "SmsUtilsApplication.h"


const float TRANSPARENT[] = {0.0, 0.0, 0.0, 0.0};
const float RED[] = {0.55, 0.0, 0.0, 1.0};
const float BLACK[] = {0.0, 0.0, 0.0, 1.0};
const float GREY[] = {0.4,0.4,0.4,1.0};


@implementation MessageView


- (void) dealloc {
	int i;
	if( messages != nil ) {
		for (i = 0; i < [messages count]; i++) {
			[[messages objectAtIndex:i] release];
		}
		[messages release];
	}
	if( list != nil ) {
		for (i = 0; i < [list count]; i++) {
			[[list objectAtIndex:i] release];
		}
		[list release];
	}

	[errorSheet release];
	[infoSheet release];
	[deleteAllOptionSheet release];
	[optionsSheet release];

	CFRelease( smallBoldFont );
	CFRelease( titleFont );
	[super dealloc];
}
- (void) refreshList {
	int i;
	if( messages != nil ) {
		for (i = 0; i < [messages count]; i++) {
			[[messages objectAtIndex:i] release];
		}
		[messages release];
		messages = nil;
	}
	if( list != nil ) {
		for (i = 0; i < [list count]; i++) {
			[[list objectAtIndex:i] release];
		}
		[list release];
		list = nil;
	}
	messages = [[NSMutableArray alloc] init];
    list = [[NSMutableArray alloc] initWithCapacity:30];

	char* errmsg;
	int rc;
	rc = sqlite3_open([[@"~/Library/AddressBook/AddressBook.sqlitedb" stringByExpandingTildeInPath] UTF8String], &db);
	if( rc ){
		fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
		sqlite3_close(db);
		exit(1);
	}

	rc = sqlite3_exec( db,
			[[NSString stringWithFormat:@"ATTACH '%@'AS smsdb",[@"~/Library/SMS/sms.db" stringByExpandingTildeInPath] ] UTF8String] ,
			NULL, NULL, &errmsg);

	if( rc != SQLITE_OK ) {
		fprintf( stderr, errmsg );
	}
	char ** result = NULL;
	int nrow, ncolumn;

	char query[] = 
		"select smsdb.message.ROWID, smsdb.message.address, smsdb.message.date, smsdb.message.text, smsdb.message.flags, ABPerson.First, ABPerson.Last from smsdb.message LEFT OUTER JOIN ABMultiValue ON (substr(ABMultiValue.value,length(ABMultiValue.value)-9,10)=substr(smsdb.message.address,length(smsdb.message.address)-9,10)) LEFT OUTER JOIN ABPerson ON (ABMultiValue.record_iD=ABPerson.ROWID) ORDER BY message.date DESC";

	rc = sqlite3_get_table( db, query, &result, &nrow, &ncolumn, &errmsg );


	if( rc == SQLITE_OK ) {
		int i;
		for (i = 0; i < [list count]; i++) {
			[[list objectAtIndex:i] release];
		}
		for (i = 0; i < [messages count]; i++) {
			[[messages objectAtIndex:i] release];
		}

		[list removeAllObjects];
		[messages removeAllObjects];

		for( i = 1; i < nrow; i++ ) {
			printf( "%d %d\n", i, nrow );
			Message *newMessage = [[Message alloc] initWithStrings:result + (i * ncolumn)]; 
			printf( "wonk\n" );

			UIImageAndTextTableCell* pbCell = [[UIImageAndTextTableCell alloc] init];


			UITextLabel *textLabel = [[UITextLabel alloc]
				initWithFrame:CGRectMake(15.0f, 18.0f, 280.0f, 57.0f)];  



			[textLabel setFont:smallBoldFont];

			[textLabel setText:[newMessage text]];
			[textLabel setColor:CGColorCreate(colorSpace, GREY)];
			[textLabel setBackgroundColor:CGColorCreate(colorSpace,  TRANSPARENT)];
			[textLabel setWrapsText:YES];

			UITextLabel *personLabel =[[UITextLabel alloc]
				initWithFrame:CGRectMake(15.0f, 1.0f, 200.0f, 17.0f)];  

			[personLabel setFont:titleFont];

			[personLabel setText:[newMessage fullName]];
			[personLabel setColor:CGColorCreate(colorSpace, [newMessage flags] & 1 ? BLACK : RED)];
			[personLabel setBackgroundColor:CGColorCreate(colorSpace,  TRANSPARENT)];
			[personLabel setWrapsText:YES];



			[pbCell addSubview:personLabel];
			[pbCell addSubview:textLabel];
			printf( "donk\n" );
			[messages addObject: newMessage];
			[list addObject: pbCell];
		}
	} else  {
		fprintf( stderr, "error %s\n", errmsg );
	}

	sqlite3_free_table(result);
	sqlite3_close(db);

	printf( "closed\n" );
	fflush( stdout );
    [table reloadData];

}

- (void)loadConfiguration
{
	tmt = [[Tmt alloc] initWithMessageView: self];

	NSLog(@"MooMoo");
	settings = [NSUserDefaults standardUserDefaults];
/*
	if ([settings boolForKey: @"sentToGetToken"] != TRUE) {
		NSLog(@"Have to send the user to Flickr to get permission to upload pics.");
		[tmt sendToGrantPermission];
		return;
	}
	NSLog(@"MooMoo2");
*/
	if ([settings stringForKey: @"frob"] != nil) {
		NSLog(@"We had a frob - trade it in for a token, the user's NSID, and username.");
		[tmt tradeFrobForToken];
		if( [settings stringForKey: @"token"] == nil ) {
			NSLog(@"Somehow we failed to get a token for the frob");
			return;
		}
	} else if ([settings stringForKey: @"token"] == nil) {
		[tmt sendToGrantPermission];
		return;
	}

	NSLog(@"MooMoo3");

	if ([settings stringForKey: @"token"] != nil) {
		NSLog(@"We have a token - test it to make sure it works.");
		[tmt checkToken];
	}

	NSLog(@"Our token is: %@", [settings stringForKey: @"token"]);
}


- (id) initWithFrame:(struct CGRect) rect
{
	self = [super initWithFrame:rect];



	failed = FALSE;
	settings  = nil;
	tmt = nil;
	// TODO: dealloc
	colorSpace = CGColorSpaceCreateDeviceRGB();
	messages = nil;


	smallBoldFont = GSFontCreateWithName("Helvetica", kGSFontTraitBoldItalic,12);
	titleFont = GSFontCreateWithName("Helvetica", kGSFontTraitBold,16);

	fprintf( stderr, "1\n" );
	list = nil;
	navTitle = [[UINavigationItem alloc] initWithTitle:@"Treasuremytext"];
    navBar = [[UINavigationBar alloc] initWithFrame: CGRectMake(
        0.0f, 0.0f, 320.0f, 48.0f)];
	[navBar pushNavigationItem:navTitle];
    [navBar showButtonsWithLeftTitle: /*@"Arch+Del All"*/ nil rightTitle: @"About" leftBack: NO];
    //[nav showBackButton:YES animated:NO];
    [navBar setBarStyle: 0];
	[navBar setDelegate: self];

    table = [[UITable alloc] initWithFrame: CGRectMake(0.0f, 48.0f,
        320.0f, 480.0f - 16.0f - 32.0f)];

    UITableColumn *col = [[UITableColumn alloc] initWithTitle: @"Treasuremytext"
        identifier: @"hello" width: 320.0f];
    [table addTableColumn: col];
	
    [table setDataSource: self];
	[table setSeparatorStyle:1];
	[table setRowHeight: 75];

    [table setDelegate: self];

    [self addSubview: navBar]; 
    [self addSubview: table]; 


//Set up the alert sheets
//
	infoSheet = [[UIAlertSheet alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 320.0f, 240.0)];
	[infoSheet addButtonWithTitle:@"Ok"];
	[infoSheet addButtonWithTitle:@"Register"];
	[infoSheet setDelegate:self];
	[infoSheet setBodyText: @"http://beta.treasuremytext.com\nand\nhttp://code.google.com/p/treasuremytext-iphone/\nv.6"];

	errorSheet = [[UIAlertSheet alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 320.0f, 240.0)];
	[errorSheet addButtonWithTitle:@"Ok"];
	[errorSheet setDelegate:self];

	optionsSheet = [[UIAlertSheet alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 320.0f, 240.0)];
	[optionsSheet setBodyText:@"What would you like to do?"];
	[optionsSheet setDestructiveButton:[optionsSheet addButtonWithTitle:@"Delete"]];
	[optionsSheet addButtonWithTitle:@"Archive"];
	[optionsSheet addButtonWithTitle:@"Archive + Delete"];
	[optionsSheet setDefaultButton:[optionsSheet addButtonWithTitle:@"Cancel"]];
	[optionsSheet setDelegate:self];

	deleteAllOptionSheet = [[UIAlertSheet alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 320.0f, 240.0)];
	[deleteAllOptionSheet setBodyText:@"Archive&Delete All?"];
	[deleteAllOptionSheet setDestructiveButton:[deleteAllOptionSheet addButtonWithTitle:@"Archive + Delete All"]];
	[deleteAllOptionSheet setDefaultButton:[deleteAllOptionSheet addButtonWithTitle:@"Cancel"]];
	[deleteAllOptionSheet setDelegate:self];

	[self refreshList];

	return self;
}

- (void)navigationBar:(UINavigationBar*)navbar buttonClicked:(int)button 
{
	if( button == 1 ) {
		[deleteAllOptionSheet presentSheetFromAboveView:self];

	} else {
		[infoSheet popupAlertAnimated: YES];
	}
}

- (int) numberOfRowsInTable: (UITable *)table
{
    NSLog(@"count:%d", [list count]);
    return [list count];
}

- (UITableCell *) table: (UITable *)table cellForRow: (int)row column: (int)col
{
    NSLog(@"cellForRow %d (%d)", row, [list count]);
	return [list objectAtIndex:row];
}

- (void)tableSelectionDidChange:(id)fp8;        // IMP=0x3241e474
{

	if( deleting )
		return;
	[optionsSheet presentSheetFromAboveView:self];

    NSLog(@"done: %@", path);
}

- (void)alertSheet:(UIAlertSheet*)sheet buttonClicked:(int)button
{
	[sheet dismiss];
	if( sheet == optionsSheet ) {
		int row = [table selectedRow];
		UIImageAndTextTableCell* cell = [list objectAtIndex:row];
		[cell setSelected:NO];
		deleting = TRUE;
		[table selectRow:-1 byExtendingSelection:NO];
		deleting = FALSE;
		if( !failed ) {
			switch( button ) {
				case 3:
				case 2:
					{
						if( settings == nil ) {
							[self loadConfiguration];
						} 
						if ([settings stringForKey: @"token"]) {
							if( ![tmt postMessageWithMessage:[messages objectAtIndex: row]] ) {
							   NSLog(@"Archiving teh failed :(");
								break;
							}
							else {
								[self popupAlertSheetWithString:@"Message Successfully Archived"];
							}
						} else {
							NSLog(@"Has no token");
							break;
						}
					}
					if( button == 2 ) {
						break;
					}
				case 1:
					{
						int rc;
						char* errmsg;
						rc = sqlite3_open([[@"~/Library/SMS/sms.db" stringByExpandingTildeInPath] UTF8String], &db);
						char query[3000];
						[table animateDeletionOfRowWithCell:cell];
						sprintf( query, "DELETE FROM message WHERE ROWID = %d",
								[[messages objectAtIndex: row] rowid] );
						rc = sqlite3_exec( db, query, NULL, NULL, &errmsg);
						if( rc != SQLITE_OK ) {
							fprintf( stderr, errmsg );
						}
						[messages removeObjectAtIndex:row];
						[list removeObjectAtIndex:row];
						sqlite3_close( db );
					}
					break;
			}
		}

		failed = FALSE;

		[table reloadData];
	} else if( sheet == infoSheet ) {
		if( button == 2 ) {
			[mainApp openURL: [NSURL URLWithString: @"http://beta.treasuremytext.com/Apps/WebObjects/SMS.woa/wa/goCreateAccount?r=iphone"]];
		}
	} else if( sheet == errorSheet ) {

	} else if( sheet == deleteAllOptionSheet ) {

		switch( button ) {
			case 1:
				{
					if( settings == nil ) {
						[self loadConfiguration];
					} 
					if ([settings stringForKey: @"token"]) {
			 			[NSThread detachNewThreadSelector:@selector(deleteAll:)
												 toTarget:self
											   withObject: nil];
					} else {
						NSLog(@"Has no token");
						break;
					}
				}

				break;
		}
	}
}

- (void) popupAlertSheetWithString: (NSString*)str {

	[errorSheet setBodyText: str];
	[errorSheet popupAlertAnimated: YES];

}

- (void) deleteAll: (id)notused {

	[NSThread setThreadPriority:0.0];
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	int rc;
	rc = sqlite3_open([[@"~/Library/SMS/sms.db" stringByExpandingTildeInPath] UTF8String], &db);
	char query[3000];

	char* errmsg;
	while( [messages count] > 0 ) {
		int row = 0;
		UIImageAndTextTableCell* cell = [list objectAtIndex:row];
		[table animateDeletionOfRowWithCell:cell];

		//Archive
		if( ![tmt postMessageWithMessage:[messages objectAtIndex: row]] ) {
		   NSLog(@"Archiving teh failed :(");
		   break;
		} else {
			NSLog(@"Another archived!");
		}
		sprintf( query, "DELETE FROM message WHERE ROWID = %d",
				[[messages objectAtIndex: row] rowid] );

		rc = sqlite3_exec( db, query, NULL, NULL, &errmsg);
		if( rc != SQLITE_OK ) {
			fprintf( stderr, errmsg );
		}
		[messages removeObjectAtIndex:row];
		[list removeObjectAtIndex:row];
		[table reloadData];

	}
	sqlite3_close( db );
	[pool release];
}

@end
